package cn.longge.controller;

import cn.longge.entity.Result;
import cn.longge.entity.SysArea;
import cn.longge.service.ISysAreaService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("manager/area")
public class AreaController {

    @Autowired
    private ISysAreaService areaService;

    @RequestMapping("index")
    public ModelAndView area(){
        return new ModelAndView("area/area");
    }

    @RequestMapping("list")
    public Result findAll(){
        List<SysArea> sysAreas = areaService.selectAll();
        return new Result(true,"success",sysAreas);
    }

    @RequestMapping("select/{page}/{pageSize}")
    public Result selectByPage(@PathVariable int page, @PathVariable int pageSize, @RequestBody Map<String,Object> params){
        PageInfo pageInfo = areaService.selectByPage(page, pageSize, params);
        Result result = new Result(true,"success",pageInfo);
        return result;
    }

    @RequestMapping("toUpdate")
    public ModelAndView toUpdate(){
        return new ModelAndView("area/save");
    }

    @RequestMapping("toIcon")
    public ModelAndView toIcon(){
        return new ModelAndView("area/modules/font-awesome");
    }

    @RequestMapping("doUpdate")
    public Result doUpdate(@RequestBody SysArea area){
        area.setUpdateDate(new Date());
        areaService.updateByPrimaryKeySelective(area);
        return new Result(true,"更新成功",null);
    }

    @RequestMapping("toSelect")
    public ModelAndView toSelect(){
        return new ModelAndView("area/select");
    }

    @RequestMapping("download")
    public void download(HttpServletResponse resp) throws IOException {
        resp.setHeader("Content-Disposition","attachment;filename=" + new String("区域管理.xlsx".getBytes(),"iso8859-1"));
        areaService.download(resp.getOutputStream());
    }

    @RequestMapping("upload")
    public void upload(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        areaService.upload(inputStream);
    }
}
